<template>
  <div>
    <!-- Sidebar -->
    <div class="sidebar">
      <div style="padding: 24px 20px; border-bottom: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center; gap: 12px;">
          <div style="width: 40px; height: 40px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: white; font-weight: bold;">快</div>
          <div style="font-weight: 600; color: #111827;">快递代拿管理系统</div>
        </div>
      </div>

      <div style="padding: 16px 0;">
        <div class="nav-section">主菜单</div>
        <button :class="['nav-item', $route.path === '/admin/dashboard' ? 'active' : '']" @click="$router.push('/admin/dashboard')"><i class="fas fa-chart-line"></i><span>数据总览</span></button>
        <button :class="['nav-item', $route.path === '/admin/orders' ? 'active' : '']" @click="$router.push('/admin/orders')"><i class="fas fa-box"></i><span>订单管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/users' ? 'active' : '']" @click="$router.push('/admin/users')"><i class="fas fa-users"></i><span>下单者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/couriers' ? 'active' : '']" @click="$router.push('/admin/couriers')"><i class="fas fa-motorcycle"></i><span>代拿者管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/finance' ? 'active' : '']" @click="$router.push('/admin/finance')"><i class="fas fa-wallet"></i><span>财务管理</span></button>

        <div class="nav-section">运营管理</div>
        <button :class="['nav-item', $route.path === '/admin/announcements' ? 'active' : '']" @click="$router.push('/admin/announcements')"><i class="fas fa-bullhorn"></i><span>公告管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/pricing' ? 'active' : '']" @click="$router.push('/admin/pricing')"><i class="fas fa-percentage"></i><span>盈利规则</span></button>

        <div class="nav-section">系统设置</div>
        <button :class="['nav-item', $route.path === '/admin/permissions' ? 'active' : '']" @click="$router.push('/admin/permissions')"><i class="fas fa-shield-alt"></i><span>权限管理</span></button>
        <button :class="['nav-item', $route.path === '/admin/logs' ? 'active' : '']" @click="$router.push('/admin/logs')"><i class="fas fa-file-alt"></i><span>系统日志</span></button>
        <button :class="['nav-item', $route.path === '/admin/settings' ? 'active' : '']" @click="$router.push('/admin/settings')"><i class="fas fa-cog"></i><span>系统设置</span></button>
      </div>

      <div style="position: absolute; bottom: 0; left: 0; right: 0; padding: 20px; border-top: 1px solid #e5e7eb;">
        <div style="display: flex; align-items: center;">
          <div style="width: 40px; height: 40px; border-radius: 50%; background:#e5e7eb; display:flex; align-items:center; justify-content:center; color:#6b7280; font-weight:600;">管</div>
          <div style="margin-left: 12px; flex: 1;">
            <div style="font-weight: 500; color: #111827; font-size: 14px;">管理员</div>
            <div style="font-size: 12px; color: #9ca3af;">超级管理员</div>
          </div>
        </div>
        <button class="nav-item" @click="confirmLogout" style="margin-top:12px;"><i class="fas fa-sign-out-alt"></i><span>退出登录</span></button>
      </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
      <!-- Header -->
      <div class="header">
        <div></div>
        <div style="position: relative;">
          <input
            v-model="searchKeyword"
            type="text"
            placeholder="搜索代拿者姓名 / 手机号..."
            style="padding: 8px 16px 8px 36px; border: 1px solid #e5e7eb; border-radius: 8px; width: 260px;"
          >
          <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #9ca3af;"></i>
        </div>
      </div>

      <!-- Page Content -->
      <div style="padding: 32px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
          <div>
            <h1 style="font-size: 28px; font-weight: 600; margin-bottom: 8px;">代拿者管理</h1>
            <p style="color: #6b7280;">管理平台所有代拿者</p>
          </div>
          <button @click="openCreate" class="btn btn-primary" style="padding: 8px 16px; background: #3b82f6; color: white; border-radius: 8px; border: none; cursor: pointer;">
            <i class="fas fa-user-plus" style="margin-right: 8px;"></i>
            添加代拿者
          </button>
        </div>

        <!-- Stats Grid -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 20px; margin-bottom: 32px;">
          <div class="stat-card">
            <div style="display:flex;justify-content:space-between;align-items:start;">
              <div>
                <div style="color:#6b7280;font-size:14px;margin-bottom:8px;">总代拿者数</div>
                <div style="font-size:28px;font-weight:700;">{{ stats.total || 0 }}</div>
              </div>
              <div style="width:48px;height:48px;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-motorcycle" style="font-size:22px;color:#3b82f6;"></i>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display:flex;justify-content:space-between;align-items:start;">
              <div>
                <div style="color:#6b7280;font-size:14px;margin-bottom:8px;">在线代拿者</div>
                <div style="font-size:28px;font-weight:700;">{{ stats.online || 0 }}</div>
              </div>
              <div style="width:48px;height:48px;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-circle" style="font-size:18px;color:#10b981;"></i>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display:flex;justify-content:space-between;align-items:start;">
              <div>
                <div style="color:#6b7280;font-size:14px;margin-bottom:8px;">配送中</div>
                <div style="font-size:28px;font-weight:700;">{{ stats.delivering || 0 }}</div>
              </div>
              <div style="width:48px;height:48px;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-shipping-fast" style="font-size:22px;color:#f59e0b;"></i>
              </div>
            </div>
          </div>
          <div class="stat-card">
            <div style="display:flex;justify-content:space-between;align-items:start;">
              <div>
                <div style="color:#6b7280;font-size:14px;margin-bottom:8px;">平均评分</div>
                <div style="font-size:28px;font-weight:700;">{{ stats.avgRating?.toFixed ? stats.avgRating.toFixed(1) : (stats.avgRating || 0) }}</div>
              </div>
              <div style="width:48px;height:48px;display:flex;align-items:center;justify-content:center;">
                <i class="fas fa-star" style="font-size:22px;color:#f59e0b;"></i>
              </div>
            </div>
          </div>
        </div>

        <!-- Couriers Table -->
        <div class="table-container">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <div style="display: flex; gap: 12px;">
              <button @click="switchTab('all')" :style="tabStyle('all')">全部代拿者</button>
              <button @click="switchTab('active')" :style="tabStyle('active')">在线代拿者</button>
              <button @click="switchTab('vip')" :style="tabStyle('vip')">核心代拿者</button>
              <button @click="switchTab('disabled')" :style="tabStyle('disabled')">已禁用</button>
            </div>
            <div style="display: flex; gap: 12px;">
              <select v-model="sortBy" @change="fetchCouriers" style="padding: 8px 12px; border: 1px solid #e5e7eb; border-radius: 8px; color: #6b7280;">
                <option value="created_at">按注册时间</option>
                <option value="orders">按接单数量</option>
                <option value="amount">按收入金额</option>
              </select>
              <button @click="exportCsv" style="color: #3b82f6; background: none; border: none; cursor: pointer;">
                <i class="fas fa-download" style="margin-right: 6px;"></i>
                导出
              </button>
            </div>
          </div>

          <table>
            <thead>
              <tr>
                <th><input type="checkbox"></th>
                <th>代拿者信息</th>
                <th>手机号码</th>
                <th>代拿等级</th>
                <th>接单数量</th>
                <th>收入金额</th>
                <th>评分</th>
                <th>注册时间</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="c in couriers" :key="c.id">
                <td><input type="checkbox"></td>
                <td>
                  <div style="display: flex; align-items: center; gap: 12px;">
                    <img :src="avatarUrl(c)" :alt="c.nickname || c.phone" style="width: 40px; height: 40px; border-radius: 50%;">
                    <div>
                      <div style="font-weight: 500;">{{ c.nickname || ('代拿者' + c.id) }}</div>
                      <div style="font-size: 12px; color: #9ca3af;">ID: {{ c.id }}</div>
                    </div>
                  </div>
                </td>
                <td>{{ c.phone || '-' }}</td>
                <td>
                  <span v-if="isVip(c)" class="badge badge-vip"><i class="fas fa-crown" style="margin-right: 4px;"></i>核心代拿者</span>
                  <span v-else class="badge">普通</span>
                </td>
                <td style="font-weight: 500;">{{ (c.actual_pickup_count != null ? c.actual_pickup_count : c.total_pickups) || 0 }}</td>
                <td style="font-weight: 600; color: #10b981;">¥{{ formatMoney((c.actual_total_income != null ? c.actual_total_income : c.total_income) || 0) }}</td>
                <td>{{ (c.rating || 0).toFixed ? c.rating.toFixed(1) : (c.rating || 0) }}</td>
                <td style="color: #6b7280;">{{ formatDate(c.created_at) }}</td>
                <td>
                  <span v-if="isActive(c)" class="badge badge-online">在线</span>
                  <span v-else class="badge">离线</span>
                </td>
                <td>
                  <div style="display: flex; gap: 8px;">
                    <button @click="openDetail(c.id)" style="color: #3b82f6; background: none; border: none; cursor: pointer;"><i class="fas fa-eye"></i></button>
                  </div>
                </td>
              </tr>
              <tr v-if="!couriers.length">
                <td colspan="10" style="text-align:center; color:#9ca3af; padding:24px;">暂无代拿者数据</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 创建代拿者弹窗 -->
        <div v-if="showCreate" style="position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; z-index:1000;">
          <div style="width: 560px; max-width: 90%; background:#fff; border-radius:12px; padding:24px;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
              <h3 style="font-size:18px; font-weight:600;">添加代拿者</h3>
              <button @click="showCreate=false" style="border:0; background:transparent; font-size:20px; line-height:1; cursor:pointer;">×</button>
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px;">
              <div style="grid-column:1/-1;">
                <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">手机号</label>
                <input v-model="form.phone" placeholder="请输入手机号" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;" />
              </div>
              <div>
                <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">昵称</label>
                <input v-model="form.nickname" placeholder="可选" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;" />
              </div>
              <div style="grid-column:1/-1;">
                <label style="display:block; font-size:12px; color:#6b7280; margin-bottom:6px;">初始密码</label>
                <input v-model="form.password" type="password" placeholder="可选" style="width:100%; padding:10px 12px; border:1px solid #e5e7eb; border-radius:8px;" />
              </div>
            </div>
            <div style="display:flex; justify-content:flex-end; gap:12px; margin-top:16px;">
              <button @click="submitCreate" style="padding: 10px 16px; background:#3b82f6; color:#fff; border:0; border-radius:8px; cursor:pointer;">创建</button>
            </div>
          </div>
        </div>

        <!-- 代拿者详情弹窗 -->
        <div v-if="showDetail" style="position:fixed; inset:0; background:rgba(0,0,0,.4); display:flex; align-items:center; justify-content:center; z-index:1000;">
          <div style="width: 720px; max-width: 90%; background:#fff; border-radius:12px; padding:24px;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px;">
              <h3 style="font-size:18px; font-weight:600;">代拿者详情 #{{ detail && detail.id }}</h3>
              <button @click="showDetail=false" style="border:0; background:transparent; font-size:20px; line-height:1; cursor:pointer;">×</button>
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px; font-size:14px; color:#374151;">
              <div><strong>昵称：</strong>{{ (detail && detail.nickname) || '-' }}</div>
              <div><strong>手机号：</strong>{{ (detail && detail.phone) || '-' }}</div>
              <div><strong>评分：</strong>{{ (detail && (detail.avg_rating ?? detail.rating)) ?? '-' }}</div>
              <div><strong>完成订单：</strong>{{ (detail && detail.completed_orders) ?? 0 }}</div>
              <div><strong>累计收入：</strong>{{ (detail && detail.total_income) ?? 0 }}</div>
              <div style="grid-column:1/-1;"><strong>服务范围：</strong>{{ (detail && detail.service_range) || '-' }}</div>
              <div style="grid-column:1/-1;"><strong>服务时间：</strong>{{ (detail && detail.service_time) || '-' }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'AdminCouriers',
  data() {
    return {
      activeTab: 'all',
      searchKeyword: '',
      sortBy: 'created_at',
      stats: {
        total: 0,
        online: 0,
        delivering: 0,
        avgRating: 0
      },
      couriers: [],
      showCreate: false,
      form: { phone: '', nickname: '', password: '' },
      showDetail: false,
      detail: null
    }
  },
  mounted() {
    this.fetchStats()
    this.fetchCouriers()
  },
  methods: {
    tabStyle(type) {
      const isActive = this.activeTab === type
      return {
        padding: '8px 16px',
        background: isActive ? '#eff6ff' : 'transparent',
        color: isActive ? '#3b82f6' : '#6b7280',
        border: 'none',
        borderRadius: '8px',
        cursor: 'pointer',
        fontWeight: isActive ? '500' : '400'
      }
    },
    switchTab(type) {
      this.activeTab = type
      this.fetchCouriers()
    },
    confirmLogout() {
      if (confirm('是否确认退出？')) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminInfo')
        localStorage.removeItem('userToken')
        this.$router.push('/login')
      }
    },
    avatarUrl(c) {
      const name = encodeURIComponent(c.nickname || c.phone || 'C')
      return `https://ui-avatars.com/api/?name=${name}&background=3b82f6&color=fff`
    },
    formatMoney(amount) {
      return (Number(amount) || 0).toFixed(2)
    },
    formatDate(s) {
      if (!s) return '-'
      try { return String(s).replace('T',' ').slice(0,19) } catch { return s }
    },
    async fetchStats() {
      try {
        const { data } = await axios.get('/api/couriers-admin/stats').catch(() => ({ data: null }))
        if (data && data.success) {
          this.stats = data.data || this.stats
        }
      } catch (e) {
        console.error('获取代拿者统计失败', e)
      }
    },
    async fetchCouriers() {
      try {
        const { data } = await axios.get('/api/couriers-admin/list', {
          params: {
            category: this.activeTab,
            keyword: this.searchKeyword || undefined,
            sortBy: this.sortBy
          }
        })
        if (data && data.success !== false) {
          this.couriers = data.data || data
        }
      } catch (e) {
        console.error('获取代拿者列表失败', e)
        alert('获取代拿者失败，请稍后再试')
      }
    },
    openCreate() {
      this.form = { phone: '', nickname: '', password: '' }
      this.showCreate = true
    },
    async submitCreate() {
      if (!this.form.phone) { alert('请输入手机号'); return }
      try {
        const { data } = await axios.post('/api/couriers/admin-create', this.form)
        if (data && data.success) {
          this.showCreate = false
          alert('创建成功')
        } else {
          alert(data.message || '创建失败')
        }
      } catch (e) {
        console.error('创建代拿者失败', e)
        alert('创建失败，请稍后再试')
      }
    },
    isVip(c) {
      const orders = Number(c.actual_pickup_count != null ? c.actual_pickup_count : c.total_pickups)
      return Number(c.credit_score) >= 90 || orders >= 20
    },
    isActive(c) {
      return c.account_status === 'active'
    },
    exportCsv() {
      if (!this.couriers.length) { alert('无可导出的数据'); return }
      const headers = ['代拿者ID','昵称','手机号','等级','接单数','收入金额','评分','状态','注册时间']
      const rows = this.couriers.map(c => [
        c.id,
        c.nickname || '-',
        c.phone || '-',
        this.isVip(c) ? '核心代拿者' : '普通',
        (c.actual_pickup_count != null ? c.actual_pickup_count : c.total_pickups) ?? 0,
        this.formatMoney((c.actual_total_income != null ? c.actual_total_income : c.total_income) || 0),
        c.rating || 0,
        this.isActive(c) ? '在线' : '离线',
        this.formatDate(c.created_at)
      ])
      const csv = [headers, ...rows].map(r => r.map(v => `"${String(v).replace(/"/g,'""')}"`).join(',')).join('\n')
      const blob = new Blob(["\ufeff" + csv], { type: 'text/csv;charset=utf-8;' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `couriers_${this.activeTab}_${Date.now()}.csv`
      a.click()
      URL.revokeObjectURL(url)
    },
    async openDetail(id) {
      try {
        const { data } = await axios.get(`/api/couriers/${id}`)
        if (data && data.success) {
          this.detail = data.data
          this.showDetail = true
        } else {
          alert('获取详情失败')
        }
      } catch (e) {
        console.error('获取代拿者详情失败', e)
        alert('获取详情失败，请稍后再试')
      }
    }
  }
}
</script>

<style scoped>
.sidebar { position: fixed; left: 0; top: 0; width: 240px; height: 100vh; background: #fff; border-right: 1px solid #e5e7eb; overflow-y: auto; }
.main-content { margin-left: 240px; min-height: 100vh; }
.nav-item { display: flex; align-items: center; padding: 12px 20px; color: #6b7280; text-decoration: none; transition: all 0.2s; cursor: pointer; width: 100%; background: transparent; border: 0; text-align: left; }
.nav-item:hover { background: #f3f4f6; color: #3b82f6; }
.nav-item.active { background: #eff6ff; color: #3b82f6; font-weight: 500; }
.nav-item i { width: 20px; margin-right: 12px; }
.nav-section { padding: 16px 20px 8px; font-size: 12px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 0.5px; }
.header { background: white; border-bottom: 1px solid #e5e7eb; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between; }
.stat-card { background: white; border-radius: 12px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.rider-card { background: white; border-radius: 12px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); transition: all 0.2s; }
.rider-card:hover { box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
.badge { display: inline-block; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: 500; }
.badge-online { background: #d1fae5; color: #059669; }
.badge-busy { background: #fef3c7; color: #d97706; }
 
.table-container { background: #fff; border-radius: 12px; padding: 24px 24px 16px; box-shadow: 0 1px 4px rgba(15,23,42,0.05); }
table { width: 100%; border-collapse: collapse; font-size: 14px; line-height: 1.6; }
thead { background: #f9fafb; }
th, td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #e5e7eb; }
th { font-weight: 500; color: #6b7280; white-space: nowrap; }
tbody tr:hover { background: #f9fafb; }

</style>
